<HTML><HEAD> <!-- ------------------------------- DICE Game: w/ Cookie HighScores ------------------------------- --> <SCRIPT LANGUAGE="JavaScript"><!-- hide from old browsers /* THE JAVASCRIPT COOKBOOK by Erica Sadun, webrx@mindspring.com Copyright (c)1998 by Charles River Media. All Rights Reserved. This applet can only be re-used or modifed by license holders of the JavaScript Cookbook CD-ROM. Credit must be given in the source code and this copyright notice must be maintained. If you do not hold a license to the JavaScript Cookbook, you may NOT duplicate or modify this code for your own use. Use at your own risk. No warranty is given or implied of the suitability of this applet for any specific application. Neither Erica Sadun nor Charles River Media will be held responsible for any unwanted effects due to the use of this applet or any derivative. */ //------------------RANDOM NUMBERS---------------------------- var js_mult1=3141 var js_mult2=5821 var js_m1=100000000 var js_m2=10000 var js_iseed=0 var js_iseed1=0 var js_iseed2=0 // Return a Random Integer between 1 and N // (adapted from cookbook standard 0 to N-1) function random(n) { if (js_iseed == 0) { now = new Date() js_iseed = now.getHours() + now.getMinutes() * 60 + now.getSeconds() * 3600 } js_iseed1 = js_iseed / js_m2 js_iseed2 = js_iseed % js_m2 var tmp = (((js_iseed2 * js_mult1 + js_iseed1 * js_mult2) % js_m2) * js_m2 + (js_iseed2 * js_mult2)) % js_m1 js_iseed = (tmp + 1) % js_m1 return (Math.floor((js_iseed/js_m1) * n) + 1) } //----------------------PATH UTILITIES-------------------------- // Get the grandparent directory and append aDir function getSibling(aDir) { var loc = ""+document.location // get this dir, then parent var base = loc.substring(0, loc.lastIndexOf("/")) base = base.substring(0, base.lastIndexOf("/")+1) return base+aDir } //------------------ARRAY CREATION---------------------------- // create an array function createArray(n) { for (var i = 0; i < n; i++) {this[i] = 0} return this } // --------------------THE DICE ROLL--------------------- // Roll the dice function roll(aform) { // Game must be started and not finished to roll if ((!gameInProgress) || (turns > 12)) { alert("No rolls left. Please start a new game.") return(false) } if (thrown) { alert("You must first assign the previous roll.") return(false) } turns++ // Determine Number of Dice and Sides var num = 5 var sides = 6 // Get the Dice Image Directory var baseRef = getSibling("GRAFX/DICE/DIE") // Frame the body var s1 = "<BODY BGCOLOR=\"ffffff\"><FONT SIZE=6 COLOR=\"770000\"><CENTER>" var s2 = "</CENTER></FONT></BODY>" // Frame the table var t1 = "<TABLE BORDER=1><TR>" var t2 = "</TABLE></TR>" // Frame the specific images var i1 = "<TD><IMG SRC=\""+baseRef var i2 = ".GIF\" HEIGHT=32 WIDTH=32></TD>" // Initialize dice window parent.JCdice.document.open() parent.JCdice.document.write(s1+t1) // set dice count to zero for (var i = 1; i <= sides; i++) dice[i] = 0 // throw the dice for (var i = 1; i <= num; i++) { var mythrow = random(sides) // throw a die dice[mythrow]++ // increment the throw counter parent.JCdice.document.write(i1+mythrow+i2) // create drawing } // Finish the dice window parent.JCdice.document.write(t2+s2) parent.JCdice.document.close() return thrown = true } // Set up Double Buttons function setupForm(t1,act1, t2,t3, act3, t4) { document.write("<tr>") document.write("<td align=right><INPUT TYPE='BUTTON' VALUE='"+t1+"' "); document.write("onClick='"+act1+"'></td>") document.write("<td><INPUT TYPE='TEXT' VALUE='' NAME='"+t2+"' SIZE=3></td>") document.write("<td align=right><INPUT TYPE='BUTTON' VALUE='"+t3+"' "); document.write("onClick='"+act3+"'></td>") document.write("<td><INPUT TYPE='TEXT' VALUE='' NAME='"+t4+"' SIZE=3></td>") document.write("</tr>") } // Set up Double Text Entries function setupForm2(t1,t2,t3,t4) { document.write("<tr>") document.write("<td align=right>"+t1+"</td>") document.write("<td><INPUT TYPE='TEXT' VALUE='0' NAME='"+t2+"' SIZE=5></td>") document.write("<td align=right>"+t3+"</td>") document.write("<td><INPUT TYPE='TEXT' VALUE='0' NAME='"+t4+"' SIZE=5></td>") document.write("</tr>") } // --------------------GAME INITIALIZATION--------------------- // Initialize Global Variables var dice = createArray(6) var thrown = false var gameInProgress = false var turns = 0 // Start a new game. function initGame() { if (gameInProgress && (turns < 13) && thrown) { if (!confirm("Game already in progress. Start over?")) return(false) } // Set all fields to zero or empty for (var i = 1; i <= 6; i++) eval("document.forms[0].count"+i+".value = ''") for (var i = 3; i <= 5; i++) eval("document.forms[0].kind"+i+".value = ''") document.forms[0].ss.value='' document.forms[0].ls.value='' document.forms[0].fh.value='' document.forms[0].sum.value='' document.forms[0].SUBTOT1.value='0' document.forms[0].SUBTOT2.value='0' document.forms[0].BONUS.value='0' document.forms[0].TOT1.value='0' document.forms[0].TOT2.value='0' // Start game with a throw thrown = false gameInProgress = true turns = 0 return roll() } // Create the Data Entry Form function createForm() { document.write("<CENTER><FORM><TABLE BORDER=2>") document.write("<TR><TD COLSPAN=4 ALIGN=CENTER><B>Dice Roll Game</B></TD></TR>") setupForm("1s","simple(1)","count1","3 of a kind","mult(3)","kind3") setupForm("2s","simple(2)","count2","4 of a kind","mult(4)","kind4") setupForm("3s","simple(3)","count3","Potsie","mult(5)","kind5") setupForm("4s","simple(4)","count4","Sm. Straight","sstraight()","ss") setupForm("5s","simple(5)","count5","Lg. Straight","lstraight()","ls") setupForm("6s","simple(6)","count6","Full House","fullhouse()","fh") document.write("<td align=right>Subtotal</td>") document.write("<td><INPUT TYPE='TEXT' NAME='SUBTOT1' SIZE=5 VALUE='0'></td>") document.write("<td align=right><INPUT TYPE='BUTTON' VALUE='Sum of Dice' ") document.write("onClick='sum()'</TD>") document.write("<td align=left><INPUT TYPE='TEXT' NAME='sum'") document.write("SIZE=3 VALUE=''></td>") setupForm2("Bonus (over 63)", "BONUS", "Subtotal", "SUBTOT2") setupForm2("Total","TOT1", "Grand Total", "TOT2") document.write("<tr><td colspan=2 align=center>") document.write("<INPUT TYPE='BUTTON' VALUE='Start New Game' ") document.write("onClick='initGame()'></td>") document.write("<td colspan=2 align=center>") document.write("<INPUT TYPE='BUTTON' VALUE='Roll Dice' ") document.write("onClick='roll()'></td></tr>") document.write("<tr><td colspan=4 align=center>-------</td></tr>") document.write("<tr><td colspan=2 align=center>") document.write("<INPUT TYPE='BUTTON' VALUE='See High Score' ") document.write("onClick='seeHigh()'></td>") document.write("<td colspan=2 align=center>") document.write("<INPUT TYPE='BUTTON' VALUE='Reset High Score' ") document.write("onClick='resetHigh()'></td></tr>") document.write("</TABLE></FORM></CENTER>") } // --------------------SCORE UPDATES--------------------- // Updates after a score on the left hand side function updateTotalsLeft(d) { // update totals var subtotal1 = parseInt(document.forms[0].SUBTOT1.value) + d var subtotal2 = parseInt(document.forms[0].SUBTOT2.value) var bonus = (subtotal1 < 63) ? 0 : 35 var total = subtotal1 + bonus var grandtotal = total + subtotal2 document.forms[0].SUBTOT1.value = subtotal1 document.forms[0].SUBTOT2.value = subtotal2 document.forms[0].TOT1.value = total document.forms[0].TOT2.value = grandtotal document.forms[0].BONUS.value = bonus } // Updates after a score on the right hand side function updateTotalsRight(d) { // update totals var subtotal1 = parseInt(document.forms[0].SUBTOT1.value) var subtotal2 = parseInt(document.forms[0].SUBTOT2.value)+d var bonus = (subtotal1 < 63) ? 0 : 35 var total = subtotal1 + bonus var grandtotal = total + subtotal2 document.forms[0].SUBTOT1.value = subtotal1 document.forms[0].SUBTOT2.value = subtotal2 document.forms[0].TOT1.value = total document.forms[0].TOT2.value = grandtotal document.forms[0].BONUS.value = bonus // High Scores if (turns > 12) setTimeout('checkHigh('+grandtotal+')',500) } // --------------------SCORING TOOLS--------------------- // Sums of ones through sixes function simple(n) { if (!thrown) { alert("You must first roll the dice") return false } if (eval("document.forms[0].count"+n+".value != ''")) { alert("You have already used this button once in this game.") return false } // Dice Value var d = dice[parseInt(n)]*parseInt(n) // update field + totals eval("document.forms[0].count"+n+".value = "+d) updateTotalsLeft(d) return thrown = false } // Multiple throws (n of a kind) function mult(n) { if (!thrown) { alert("You must first roll the dice") return false } if (eval("document.forms[0].kind"+n+".value != ''")) { alert("You have already used this button once in this game.") return false } // Find the greatest multiple var m = 0 for (var i = 1; i <= 6; i++) if (dice[i] > m) m = dice[i] // Find the sum of the dice var sum = 0 for (var i = 1; i <= 6; i++) sum += i*dice[i] // Check for n of a kind if (n == 3) {if (m >= 3) d = sum; else d = 0} else if (n == 4) {if (m >= 4) d = sum; else d = 0} else if (n == 5){if (m >= 5) d = 50; else d = 0} // update field & totals eval("document.forms[0].kind"+n+".value = "+d) updateTotalsRight(d) return thrown = false } // Sum of Dice function sum() { if (!thrown) { alert("You must first roll the dice") return false } if (document.forms[0].sum.value != '') { alert("You have already used this button once in this game.") return false } // Find the sum var sum = 0 for (var i = 1; i <= 6; i++) sum += i*dice[i] // update field & totals document.forms[0].sum.value = sum updateTotalsRight(sum) return thrown = false } // Full House function fullhouse() { if (!thrown) { alert("You must first roll the dice") return false } if (document.forms[0].fh.value != '') { alert("You have already used this button once in this game.") return false } // Find the two and three var two = 0 for (var i = 1; i <= 6; i++) if (dice[i] == 2) two = i var three = 0 for (var i = 1; i <= 6; i++) if (dice[i] == 3) three = i if ((two != 0) && (three != 0)) d = 25; else d = 0 // update field & totals document.forms[0].fh.value = d updateTotalsRight(d) return thrown = false } // Large Straight function lstraight() { if (!thrown) { alert("You must first roll the dice") return false } if (document.forms[0].ls.value != '') { alert("You have already used this button once in this game.") return false } // Assure all are ones for lower or upper var lower = true for (var i = 1; i <= 5; i++) if (dice[i] == 0) lower = false var upper = true for (var i = 2; i <= 6; i++) if (dice[i] == 0) upper = false if (lower || upper) d = 40; else d = 0 // update field & totals document.forms[0].ls.value = d updateTotalsRight(d) return thrown = false } // Small Straight function sstraight() { if (!thrown) { alert("You must first roll the dice") return false } if (document.forms[0].ss.value != '') { alert("You have already used this button once in this game.") return false } // check lower then middle then upper var lower = true for (var i = 1; i <= 4; i++) if (dice[i] == 0) lower = false var middle = true for (var i = 2; i <= 5; i++) if (dice[i] == 0) middle = false var upper = true for (var i = 3; i <= 6; i++) if (dice[i] == 0) upper = false if (upper || middle || lower) d = 30; else d = 0 // update field & totals document.forms[0].ss.value = d updateTotalsRight(d) return thrown = false } // --------------------COOKIE STRING UTILITIES--------------------- // These routines have been edited for this application. Please see // ../COOKIES/COOKIE.HTM for the complete cookie collection. // --------------------COOKIE STRING UTILITIES--------------------- // Substitute character string c2 for every c1 in aString function subst(aString, c1, c2) { if (aString == "") return aString if (c1 == "") return aString // avoid infinite recursion when substituting aa for a by // providing an offset into the string. var argc = subst.arguments.length if (argc < 4) {n = 0} else {n = subst.arguments[3]} // find the first occurence of c1 after the threshold var i = aString.indexOf(c1, n) // stop recursion and return the current string when c1 not found if (i < 0) return aString // extract substrings s1 and s2 around the c1 var s1 = aString.substring(0, i) var s2 = aString.substring(i+c1.length, aString.length) // recurse with this new string return subst(s1+c2+s2, c1, c2, (i+c2.length)) } // Strips a string of blanks on either end function stripBlanks(aString) { var tmp = ""+aString var bottom = 0 var top = tmp.length if (tmp == "") return tmp while (tmp.substring(bottom, bottom + 1) == " ") bottom++ if (bottom >= top) return("") while (tmp.substring(top - 1, top) == " ") top -= 1 return (tmp.substring(bottom, top)) } // Count Occurances of a Substring function count(aString, aSubstring) { // initialize counter and offset var count = 0 var offset = 0 var where = 0 var tmp = ""+aString // search until no more found while ((offset < tmp.length) && ((where = tmp.indexOf(aSubstring, offset)) >= 0)) { count++ offset = where+aSubstring.length } // return it return count } // Encookie -- code spaces, semicolons and commas function encookie(aString) { var tmp = ""+aString tmp = subst(tmp, " ", "%20") tmp = subst(tmp, ",", "%2C") tmp = subst(tmp, ";", "%3B") tmp = subst(tmp, "=", "%3D") return tmp } // Decookie -- decode spaces, semicolons and commas function decookie(aString) { var tmp = ""+aString tmp = subst(tmp, "%20", " ") tmp = subst(tmp, "%2C", ",") tmp = subst(tmp, "%3B", ";") tmp = subst(tmp, "%3D", "=") return tmp } // Search for a substring and chop before it function chopit(aString, aSubstring) { var tmp = ""+aString if (tmp.length == 0) return tmp if (aSubstring.length == 0) return tmp var where if ((where = tmp.indexOf(aSubstring)) < 0) return tmp return (tmp.substring(0, where)) } // Search for a substring and lop off everything after it function lopit(aString, aSubstring) { var tmp = ""+aString if (tmp.length == 0) return tmp if (aSubstring.length == 0) return tmp var where if ((where = tmp.indexOf(aSubstring)) < 0) return tmp return (tmp.substring(where+aSubstring.length, tmp.length)) } //------------------STRING-ARRAY UTILITIES------------------- // Find the substring at index n, counting 0 to n function doIndex(aString, n) { var str=""+aString // Count until the correct index for(var i = 0; i < n; i++) { var where = str.indexOf(':', 1) str = str.substring(where+1, str.length) } // Lop off the end of the string return str.substring(0, str.indexOf(':')) } //------------------CUSTOM GMT UTILITY----------------------------- // Return the 3-letter symbol for month #n function month(n) { var m = "Jan:Feb:Mar:Apr:May:Jun:Jul:Aug:Sep:Oct:Nov:Dec:" return doIndex(m, n) } // Return the 3-letter symbol for day #n function day(n) { var d = "Sun:Mon:Tue:Wed:Thu:Fri:Sat:" return doIndex(d, n) } // A Custom "GMT" Function function myGMT(d) { tmp = day(d.getDay())+', '+d.getDate()+' '+month(d.getMonth()) tmp += ' 19'+d.getYear()+' ' if (d.getHours() < 10) tmp += '0' tmp += d.getHours()+':' if (d.getMinutes()< 10) tmp += '0' tmp += d.getMinutes()+':' if (d.getSeconds() < 10) tmp += '0' tmp += d.getSeconds()+" GMT" return tmp } // An Alternate "GMT" Function: NOTE! This--changed for hyphens and no (19) function altGMT(d) { tmp = day(d.getDay())+', '+d.getDate()+'-'+month(d.getMonth()) tmp += '-'+d.getYear()+' ' if (d.getHours() < 10) tmp += '0' tmp += d.getHours()+':' if (d.getMinutes()< 10) tmp += '0' tmp += d.getMinutes()+':' if (d.getSeconds() < 10) tmp += '0' tmp += d.getSeconds() return tmp } // --------------------COOKIE DATA UTILITIES--------------------- // Cookie Flattener function flatten() { var tmp = ""+this.name+"="+this.value tmp += (this.expires == null) ? "" : "; expires="+this.expires tmp += (this.path == null) ? "" : "; path="+this.path tmp += (this.domain == null) ? "" : "; domain="+this.domain tmp += (this.isSecure) ? "; secure" : "" return tmp } // Store Cookie in the jar function store() {document.cookie = this.flatten()} // Set Name function setName(aName){this.name = encookie(aName)} // Set Value function setValue(aValue){this.value = encookie(aValue)} // Get Name function getName(aName){this.name = decookie(aName)} // Get Value function getValue(aValue){this.value = decookie(aValue)} // Check for WIN16 -- avoid the date bug function isWin16() { return (navigator.userAgent.toUpperCase().indexOf('WIN16') != -1) } // Expiration Times function setExpires(howLong) { var now = new Date() var epoch = isWin16() ? 0 : new Date(0) var msecs = now.getTime() var offset = now.getTimezoneOffset() * 60000 var t = 0 howLong = howLong.toLowerCase() // determine how long until expiration if (howLong == 'now') t = msecs - (3600000 * 24 * 365) // overkill if (howLong == 'hour') t = msecs + (3600000) // 60 minutes if (howLong == 'day') t = msecs + (3600000 * 24) // 24 hours if (howLong == 'week') t = msecs + (3600000 * 24 * 7) // 7 days if (howLong == 'month') t = msecs + (3600000 * 24 * 30) // 30 days if (howLong == 'year') t = msecs + (3600000 * 24 * 365) // 365 days // set the expiration exp = isWin16() ? (t - offset) : ((t - epoch.getTime()) - offset) now.setTime(exp) this.expires = myGMT(now) return this } // Turn on security function secure(){this.isSecure = true} // Turn off security function unsecure(){this.isSecure = false} // get rid of a cookie right now function crumble() { this.setExpires('now') this.store() } // revive a crumbled cookie function uncrumble() { this.expires = null this.store() } // Cookie Constructor function JSCCookie(cname, cvalue) { // Create and initialize cookie slots this.name = encookie(cname) // readable and writeable this.value = encookie(cvalue) // readable and writeable this.expires = null // writeable this.isSecure = false // writeable this.path = null // writeable this.domain = null // writeable // Set cookie methods this.setExpires = setExpires this.crumble = crumble this.uncrumble = uncrumble this.flatten = flatten this.store = store this.secure = secure this.unsecure = unsecure this.setName = setName this.getName = getName this.setValue = setValue this.getValue = getValue } // --------------------COOKIE JAR UTILITIES--------------------- // find a cookie by partial string function findCookie(name) { num_in_jar = Math.min(document.cookie.length, count(document.cookie, ';')+1) if (num_in_jar != 0) { var tmp = ""+document.cookie for (var i = 0; i < num_in_jar; i++) { var crumb = stripBlanks(chopit(tmp, ";")) tmp = lopit(tmp, ";") var cname = decookie(chopit(crumb, "=")) if (cname.indexOf(name) >= 0) return crumb } } return null } // Fetch a value (by partial string) function fetch(name) { var crumb = findCookie(name) if (crumb == null) return null var cname = decookie(chopit(crumb, "=")) var cvalue = decookie(lopit(crumb, "=")) if (cname.indexOf(name) >= 0) return cvalue return null } // Fetch a name (by partial string) function fetchName(name) { var crumb = findCookie(name) if (crumb == null) return null var cname = decookie(chopit(crumb, "=")) var cvalue = decookie(lopit(crumb, "=")) if (cname.indexOf(name) >= 0) return cname return null } // Fetch a particular cookie (by partial string) function fetchCookie(name) { var crumb = findCookie(name) if (crumb == null) return null var cname = decookie(chopit(crumb, "=")) var cvalue = decookie(lopit(crumb, "=")) if (cname.indexOf(name) >= 0) { var c = new JSCCookie(cname, cvalue) return c } return null } // --------------------COOKIE INFO UTILITIES--------------------- // Cookie Information function cookiePeek() { size_in_jar = document.cookie.length num_in_jar = Math.min(document.cookie.length, count(document.cookie, ';')+1) if (num_in_jar != 0) { // document.write("<b>Current Cookies:</b> "+ // document.cookie+"<p><blockquote>") var tmp = ""+document.cookie var crumb, cname, cvalue for (var i = 0; i < num_in_jar; i++) { crumb = chopit(tmp, ";") tmp = lopit(tmp, ";") cname = decookie(chopit(crumb, "=")) cvalue = decookie(lopit(crumb, "=")) if(cname.indexOf("Hi") != -1) { document.write("<b>Name:</b> <FONT COLOR='770000'>"+cname+"</FONT> ") document.write("<b>Value:</b> <FONT COLOR='770000'>"+cvalue+"<br></FONT>") } } document.write("</blockquote>") } else document.write("<b>The Cookie Jar is <FONT COLOR='770000'>Empty</FONT>.</b><br>") document.write('There are a total of '+num_in_jar+' cookies taking up '+ size_in_jar+' bytes<p>') } // --------------------SCORE UTILITIES--------------------- // Set the expiration and store function saveScores() { hiScore.path = '/' hiScore.setExpires('year') hiScore.store() hiName.path = '/' hiName.setExpires('year') hiName.store() } // View the current high score function seeHigh() { alert('High Score: '+decookie(hiScore.value)+ ' set by '+decookie(hiName.value)) } // Reset the high scores function resetHigh() { if (confirm('Really reset high scores?')) { hiScore.setValue('0') hiName.setValue('[Nobody]') saveScores() } } // Determine if this score is a new high value function checkHigh(aValue) { if (aValue > parseInt(hiScore.value)) { hiScore.setValue(""+aValue) var name = prompt('You have set a new high score! '+ 'Please enter your name for posterity', '[Nobody]') if (name == null) name = '[Nobody]' hiName.setValue(""+name) saveScores() } } <!-- done hiding --></SCRIPT></HEAD> <BODY bgcolor="ffffff"> <FONT COLOR="007777"><H1><IMG SRC="../GRAFX/SPICE.JPG" WIDTH=37 HEIGHT=72 ALIGN = LEFT>"Potsie" with high scores</H1></FONT> <BLOCKQUOTE><FONT COLOR="770000"> This version of Potsie stores high scores using Cookies. </FONT></BLOCKQUOTE> <BR><BR> <SCRIPT> createForm() cookiePeek() var hiScore = fetchCookie('HiScore') var hiName = fetchCookie('HiName') if (hiScore == null) { hiScore = new JSCCookie('HiScore', '0') hiName = new JSCCookie('HiName', '[Nobody]') saveScores() } </SCRIPT> <FONT COLOR="007777"><H2>Discussion</H2></FONT> <FONT SIZE=4> This applet uses the JavaScript Cookbook cookie routines to store and recover high scores. </FONT> <PRE><FONT COLOR="770000" SIZE=3> function saveScores() { hiScore.setExpires('year') hiScore.path = '/' hiScore.store() hiName.setExpires('year') hiName.path = '/' hiName.store() } </FONT></PRE> <h5>Copyright ©1996 by Charles River Media, All Rights Reserved</h5> </BODY> </HTML>